import { StoreDefinition, defineStore } from "pinia";
// @ts-ignore
import themes from "@/themes/index.ts";
let defaultTheme = themes[0];

let arr: Array<ThemeType> = [];
themes.forEach((element: any) => {
  arr.push({
    englishName: element.englishName,
    chineseName: element.chineseName,
  });
});

interface ThemeType {
  englishName: string;
  chineseName: string;
}
interface Setting {
  theme: ThemeType;
  themeList: Array<ThemeType>;
  isSideBarCollapse: boolean;
}
const useSettingstore:StoreDefinition<string,Setting> = defineStore({
  id: "setting",
  state: (): Setting => {
    return {
      theme: { englishName: "", chineseName: "" },
      themeList: arr,
      isSideBarCollapse: false,
    };
  },
  getters: {},
  actions: {
    switchCollapse() {
      this.isSideBarCollapse = !this.isSideBarCollapse;

     
    },
    /**
     * 获取主题名
     * @returns
     */
    getTheme(): ThemeType {
      if (this.theme) {
        return this.theme;
      }
      let theme = localStorage.getItem("theme");
      if (theme) {
        this.setTheme(theme);
        return JSON.parse(theme);
      } else {
        this.setTheme(defaultTheme.englishName);
        return defaultTheme;
      }
    },
    /**
     * 切换主题
     * @param theme1
     * @param theme2
     */
    switchTheme(theme1: string, theme2: string) {
      if (theme2 == undefined || theme1 == undefined) {
        console.error("缺少主题配置");
        return;
      }
      if (this.getTheme().englishName === theme1) {
        this.setTheme(theme2);
      } else {
        this.setTheme(theme1);
      }
    },
    /**
     * 设置主题
     * @param themeName
     */
    setTheme(themeName?: string) {
      if (!themeName) {
        let themeStorage = JSON.parse(localStorage.getItem("theme") || "{}");
        themeName = themeStorage.englishName;
      }
      if (!themeName) {
        themeName = defaultTheme.englishName;
      }
      if (!themeName) {
        console.error("缺少主题配置");
        return;
      }
      if (this.theme.englishName === themeName) {
        return;
      }
      if (themeName) {
        let theme = this.themeList.find(
          (item) => item.englishName === themeName
        );
        if (theme) {
          localStorage.setItem("theme", JSON.stringify(theme));
          document.documentElement.className = "theme-" + themeName;
          this.theme = theme;
        }
      }
    },
  },
});

export default useSettingstore;

